﻿using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace SlopeIntercept {

    public class Lane {

        private float CarSpeed = 100.0f;

        private Point P1;
        private Point P2;
        private float Slope;
        public IList<GameObject> GameObjects = new List<GameObject>();
        private float Height;

        public Lane(Point p1, Point p2) {
            P1 = p1;
            P2 = p2;
            Slope = (((float)P1.Y-P2.Y)/(P1.X-P2.X));
            Height = p2.Y-p1.Y;
        }

        public static float CalculateX(float slope, Point anyPointOnLine, float currentY) {
            return ((currentY-anyPointOnLine.Y)/slope)+anyPointOnLine.X;
        }

        public void Update(GameTime gameTime) {
            foreach (GameObject gameObject in GameObjects) {
                float speed = gameObject.Speed+CarSpeed; // Current speed. Either object or car could change at any time.
                float scale = (gameObject.Position.Y-P1.Y)/Height; // Objects move faster as they get closer.
                float yDelta = speed * scale * .1f;
                if (yDelta < 1f) {
                    yDelta = 1f;
                }
                gameObject.Scale = scale;
                gameObject.Position.Y += yDelta;
                if (gameObject.Position.Y > Game1.SCREEN_BOTTOM_Y) {
                    gameObject.Position.Y = P1.Y;
                    gameObject.IsActive = false;
                } else {
                    gameObject.Position.X = CalculateX(Slope, P2, gameObject.Position.Y);
                    gameObject.IsActive = true;
                }
            }
        }

        public void Draw(SpriteBatch spriteBatch) {
            foreach (GameObject gameObject in GameObjects) {
                if (gameObject.IsActive) {
                    Vector2 adjustedPosition = gameObject.Position;
                    adjustedPosition.Y -= gameObject.Texture.Height*gameObject.Scale*2.5f; // This moves the object up so that the bottom rides on the lane.
                    spriteBatch.Draw(gameObject.Texture, adjustedPosition, null, Color.White, 0f, Vector2.Zero, gameObject.Scale, SpriteEffects.None, 0f);
                }
            }
        }

    }

}